<template>
  <div class="container">
    <div class="search-box">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名称">
          <el-input
            v-model="searchForm.nickname"
            placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input
            v-model="searchForm.id"
            placeholder="请输入用户ID"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-box clearfix">
      <div class="button-box clearfix">
        <el-button type="primary" @click="handleAdd">添加轮播图</el-button>
        <el-button type="danger" @click="handleDeleteList">批量删除</el-button>
      </div>
      <el-table
        border
        :data="userList"
        style="width: 100%  min-height: 400px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column
          v-for="column in tableColumns"
          :key="column.prop"
          :prop="column.prop"
          :label="column.label"
          align="center"
          show-overflow-tooltip
        />
        <el-table-column label="操作" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button size="mini" @click="handleEdit(scope.row)"
              >修改</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <!-- 抽屉组件 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawerVisible"
      size="30%"
      :before-close="handleClose"
    >
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="用户头像" prop="avatar_url">
          <img
            v-if="isView && form.avatar_url"
            :src="form.avatar_url"
            class="avatar"
          />

          <el-upload
            v-else
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :on-error="handleError"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :on-change="beforeAvatarUpload"
          >
            <img v-if="form.avatar_url" :src="form.avatar_url" class="avatar" />
            <i class="el-icon-plus avatar-uploader-icon position"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户昵称" prop="nickname">
          <el-input v-model="form.nickname" :disabled="isView"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" :disabled="isView"></el-input>
        </el-form-item>
        <el-form-item label="居住地" prop="userCol03">
          <el-input v-model="form.userCol03" :disabled="isView"></el-input>
        </el-form-item>
        <el-form-item label="联系地址" prop="userCol02">
          <el-input v-model="form.userCol02" :disabled="isView"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button v-if="!isView" @click="handleClose">取消</el-button>
          <el-button v-if="!isView" type="primary" @click="submitForm('form')"
            >确定</el-button
          >
          <el-button @click="handleClose">关闭</el-button>
        </span>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from "vuex";

export default {
  name: "UserManagement",

  data() {
    return {
      searchForm: {
        nickname: "",
        id: "",
      },
      userList: [],
      tableColumns: [
        { prop: "id", label: "用户ID" },
        { prop: "nickname", label: "用户昵称" },
        { prop: "username", label: "用户名称" },
        { prop: "phone", label: "用户手机号" },
        { prop: "address", label: "用户地址" },
      ],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      form: {},
      drawerTitle: "添加用户",
      drawerVisible: false,
      isView: false,
      rules: {
        nickname: [
          { required: true, message: "请输入用户昵称", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入用户手机号", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["tableColumnLabels"]),
  },
  created() {
    this.fetchUserList();
  },
  methods: {
    fetchUserList() {
      // 模拟异步请求
      //   this.$axios
      //     .get("/api/users", {
      //       params: {
      //         ...this.searchForm,
      //         page: this.currentPage,
      //         pageSize: this.pageSize,
      //       },
      //     })
      //     .then((response) => {
      //       this.userList = response.data.list;
      //       this.total = response.data.total;
      //     })
      //     .catch((error) => {
      //       console.error("获取用户列表失败", error);
      //     });
      let res = {
        data: [
          {
            id: 2,
            username: "username02",
            email: null,
            phone: "181****7412",
            created_at: "2025-04-28 22:28:46",
            avatar_url: "http://139.224.250.70:8000/storage/uploads/user/2.jpg",
            userCol02: "湖里区",
            userCol03: "厦门",
            userCol04: null,
            userCol05: null,
            userCol06: null,
            userCol07: null,
            userCol08: null,
            userCol09: null,
            nickname: "吃糖豆",
          },
        ],
      };
      this.userList = res.data.map((item) => ({
        ...item,
        address: `${item.userCol03}${item.userCol02}`,
      }));
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchUserList();
    },
    resetSearch() {
      this.searchForm = {
        nickname: "",
        id: "",
      };
      this.fetchUserList();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchUserList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchUserList();
    },
    handleAdd() {
      this.isView = false;
      this.drawerTitle = "添加用户";
      this.form = {
        avatar_url: "",
        nickname: "",
        phone: "",
        userCol03: "",
        userCol02: "",
      };
      this.drawerVisible = true;
    },
    handleView(row) {
      this.isView = true;
      this.drawerTitle = "查看用户";
      this.form = { ...row };
      this.drawerVisible = true;
    },
    handleEdit(row) {
      this.isView = false;
      this.drawerTitle = "编辑用户";
      this.form = { ...row };
      this.drawerVisible = true;
    },
    handleDelete() {
      // 删除逻辑
      // 模拟删除
      this.$confirm("确定要删除该用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$message({
          type: "success",
          message: "用户删除成功！",
        });
      });
    },
    handleClose() {
      this.drawerVisible = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.drawerTitle === "添加用户") {
            // 处理添加逻辑
            console.log("添加用户", this.form);
          } else if (this.drawerTitle === "编辑用户") {
            // 处理编辑逻辑
            console.log("编辑用户", this.form);
          }
          this.drawerVisible = false;
          this.fetchUserList();
        } else {
          console.log("表单验证失败");
          return false;
        }
      });
    },
    async handleAvatarSuccess(res, file) {
      // this.addBanner.bannerUrl = response.data.url
      //上传成功处理
      //
      // this.imageUrl = URL.createObjectURL(file.raw)
      // 创建formdata对象
      this.editInfo.avatarUrl =
        process.env.VUE_APP_PROXY_NETWORK_TARGET + res.data.url;
      return this.$message.success({
        title: "成功",
        message: "文件上传成功",
        duration: 2000,
      });
    },
    beforeAvatarUpload(file) {
      // 处理头像上传逻辑
      console.log("上传头像", file);
      return false;
    },
    handleError(err) {
      //上传失败处理
      return this.$message.error({
        title: "上传失败",
        message: "文件上传失败",
        duration: 3000,
      });
    },
    beforeAvatarUpload(file) {
      // const isLt2M = file.size / 1024 / 1024 < 4

      // if (!isLt2M) {
      //     this.$message.error('上传头像图片大小不能超过 4MB!')
      // }
      this.file = file;
      setTimeout(() => {
        this.submitFile();
      }, 500);
      // return isLt2M
    },
    async getUserInfo() {
      let res = await getUserInfo();
      if (res.code == 200) {
        this.acUserInfo(res.data);
        // 本地存储
        localStorage.setItem("userInfo", JSON.stringify(res.data));
      }
    },
    async submitFile() {
      const formData = new FormData();
      // 按照后端要求，将文件添加到formdata中，key为'image'
      formData.append("image", this.file.raw);

      await uploadAvatar(formData).then((res) => {
        this.form.avatar_url =
          process.env.VUE_APP_PROXY_NETWORK_TARGET + res.data.url;
      });
    },
    // 处理表格选中变化
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
    },
    handleDeleteList() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning("请选择需要删除的用户");
        return;
      }
      this.$confirm("确定要删除选中的用户吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id);
          // 模拟异步请求
          // this.$axios.delete('/api/users/batch', { data: { ids } })
          //   .then(() => {
          //     this.$message.success('批量删除成功');
          //     this.fetchUserList();
          //   })
          //   .catch(error => {
          //     console.error('批量删除失败', error);
          //     this.$message.error('批量删除失败');
          //   });
          // 模拟成功响应
          console.log("批量删除用户 ID:", ids);
          this.$message.success("批量删除成功");
          this.fetchUserList();
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.table-box {
  .el-table {
    margin-bottom: 20px;
  }
}

.avatar-uploader {
  width: 130px;
  height: 130px;
}
::v-deep .avatar-uploader .el-upload {
  width: 130px;
  height: 130px;
  border: 1px dashed #333333;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  position: relative;
  width: 130px;
  height: 130px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 130px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 130px;
  height: 130px;
  display: block;
}
.position {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -68%);
}
</style>
